"""
@Project ：zzzr_api_test 
@File    ：case.py
@IDE     ：PyCharm 
@Author  ：ZSR
@Date    ：2023/2/28 22:48 
"""

from tool.assert_ import Assert
from tool.parameter_setting import ParameterSetting
from tool.request_ import Requests
from tool.log import logger
from tool.allure_ import allure_description


def replace_(extract_key, api_response):
    """参数提取处理"""
    # 判断是否有参数提取
    logger.info(f'提取参数字典{extract_key}')
    if extract_key:
        # 把表达式替换为具体的值
        extract_value = ParameterSetting.extract_value(api_response, extract_key)
        # 参数提取到参数池
        ParameterSetting.parameter_setting(extract_value, 'save')


def case_assert_result(case_data):
    """
    :param case_data: yaml 读取的用例数据
    :return:  get请求还没写参数依赖
    """

    allure_description(case_data['remark'])
    logger.info(f'\n用例初始数据:\n{case_data}')
    if case_data['method'] == 'get':
        api_response = Requests.get(case_data['path'])
        extract_key = case_data['extract_key']
        replace_(extract_key, api_response)
        assert_result = Assert.assert_response(case_data['assert_expression'], api_response)
    else:
        ''' 参数替换和参数依赖操作必须在同一个页面中，不然切面切换参数池会置空{}'''
        # 判断是否需要替换请求参数
        if ParameterSetting.data_is_replace(case_data['data']):
            # 参数替换
            case_data['data'] = ParameterSetting.parameter_setting(case_data['data'])

        data = case_data['data']
        api_response = Requests.post(case_data['path'], data, case_data['headers'])
        extract_key = case_data['extract_key']
        # 判断是否有后置参数提取
        replace_(extract_key, api_response)
        logger.info(f'\n用例提取的参数字典:\n{extract_key}')
        assert_result = Assert.assert_response(case_data['assert_expression'], api_response)

    case_title = case_data['case_title']
    logger.info(f'\n------\t{case_title}\t用例运行完成 ------')
    return assert_result
